package com.my.mail2.loadblanch;

import com.my.mail2.service.IEmailService;
import com.my.mail2.service.impl.AbstractEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 加权随机负载均衡
 */
@Primary
@Component
public class RandomLoadBalance implements ILoadBalance {

    @Autowired
    private List<AbstractEmailService> emailServiceChain;

    /**
     * 静态负载均衡
     */
    List<AbstractEmailService> emailServiceList = new ArrayList<>();

    @PostConstruct
    private void init() {
        for (AbstractEmailService service : emailServiceChain) {
            for (int i = 0; i < service.getWeight(); i++) {
                emailServiceList.add(service);
            }
        }
    }

    @Override
    public IEmailService select() {
        int chosenIndex = ThreadLocalRandom.current().nextInt(0, this.emailServiceList.size());
        return emailServiceList.get(chosenIndex);
    }
}
